package javaCode;

public class LeetCode581 {
	public int findUnsortedSubarray(int[] nums) {
		if(nums == null || nums.length == 1){
			return 0;
		}
		int start = 0;
		int end = 0;
		for(int i = 1;i < nums.length;i++){
			if(nums[i] < nums[i-1]){
				start = i-1;
				break;
			}
		}
		for(int i = nums.length-1;i > start;i--){
			if(nums[i] < nums[i-1]){
				end = i;
				break;
			}
		}
		if(start == end){
			return 0;
		}
		int min = nums[start];
		int max = nums[end];
		for(int i = start;i <= end;i++){
			if(min > nums[i]){
				min = nums[i];
			}
			if(max < nums[i]){
				max = nums[i];
			}
		}
		for(int i = 0;i < nums.length;i++){
			if(min < nums[i]){
				start = i;
				break;
			}
		}
		for(int i = nums.length-1;i > 0;i--){
			if(max > nums[i]){
				end = i;
				break;
			}
		}
		return end-start+1;
	}
}
